﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IllustratedCsharp7_ch15
{
    /*事件中的5个部分
        1,委托类型声明
        2，事件声明
        3，事件注册
        4，事件处理程序
        5，触发事件的代码
     */
    delegate void Handler();        //声明委托
    /*
        发布者类Incrementer
        定义了一个CountedAdozen事件，每次累积到12个项时将会触发该事件
        订阅者类Dozens注册到CountedADozen事件
        每当触发事件时，都会调用这些处理程序
     */
    class Incrementer
    {
        public event Handler CountedADozen; //创建事件并发布

        public void DoCount()
        {
            for (int i = 1; i < 100; i++)
                if (i % 12 == 0 && CountedADozen != null)
                    CountedADozen(); //每增加12个计数触发事件一次
        }
    }
    /*
     订阅者类Dozens
    注册到CountedADozen事件
     */
    class Dozens
    { 
        public int DozensCount { get; private set; }
        public Dozens(Incrementer incrementer)
        {
            DozensCount = 0;
            incrementer.CountedADozen += IncrementDozensCount; //订阅事件
        }

        void IncrementDozensCount() //声明事件处理程序
        {
            DozensCount++;
        }
    }
    class chapt15_1to5_Event
    {
        static void _Main()
        {
            Incrementer incrementer = new Incrementer();
            Dozens dozensCounter = new Dozens(incrementer);

            incrementer.DoCount();
            Console.WriteLine("Number of dozens = {0}", dozensCounter.DozensCount);
        }
    }
}
